package com.binguo.api.controller;

import com.binguo.api.businessmodel.ProductImgModel;
import com.binguo.api.form.ProductCorrectForm;
import com.binguo.api.form.localrec.DeviceForm;
import com.binguo.api.form.localrec.RecResultRequest;
import com.binguo.api.response.product.ProductRecResultVONewWithLocation;
import com.binguo.api.response.product.ShopProductMessageVO;
import com.binguo.api.result.Result;
import com.binguo.api.result.ResultGenerator;
import com.binguo.api.schedule.DataLoadService;
import com.binguo.api.service.local.LocalService;
import com.binguo.common.util.JsonUtil;
import com.binguo.model.mapper.ShopLocalIpMapper;
import com.binguo.model.model.*;
import com.binguo.model.repository.AdvertRepository;
import com.binguo.model.repository.ProductYpRefRepository;
import com.fasterxml.jackson.core.JsonProcessingException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Decoder;
import tk.mybatis.mapper.entity.Condition;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;

@RestController
@RequestMapping
public class LocalRecController {
    private static Logger logger = LoggerFactory.getLogger(LocalRecController.class);

    @Autowired
    LocalService localService;

    @Autowired
    ProductYpRefRepository productYpRefRepository;


    private List<Integer> directoryCreatedShopIdList = new ArrayList<>();

    private String ipAddress;

    private BASE64Decoder decoder = new BASE64Decoder();

    public LocalRecController(){
        this.ipAddress = System.getenv().get("ipAddress");
    }

    @PostMapping(value = "/api/local/getIpList", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "获取ip列表")
    public Result getIpList(@RequestBody DeviceForm deviceForm){

        return localService.getIpList(deviceForm.getIp(), deviceForm.getDeviceId(), deviceForm.getBranchId());
    }


    @PostMapping(value = "/api/local/getYpProductList", produces = APPLICATION_JSON_VALUE)
    public Result getYpProductList(@RequestParam("branchId") Integer branchId){
        Condition condition = new Condition(ProductYpRef.class);
        condition.or().andEqualTo("branchId", branchId);
        List<ProductYpRef> productYpRefList = productYpRefRepository.findByCondition(condition);

        if (productYpRefList != null && productYpRefList.size() > 0) {
            return ResultGenerator.genSuccessResult(productYpRefList);
        }
        return ResultGenerator.genFailResult(null);
    }


    @PostMapping(value = "/api/local/getProductImgList", produces = APPLICATION_JSON_VALUE)
    public Result getProductImgList(@RequestParam("branchId") Integer branchId){

        List<ShopProductMessage> shopProductMessages = localService.getMessageList(branchId);

        if (shopProductMessages != null && shopProductMessages.size() > 0) {
            return ResultGenerator.genSuccessResult(
                    shopProductMessages.stream().map(shopProductMessage ->
                ShopProductMessageVO.builder().pId(shopProductMessage.getProductId())
                                .msgType(shopProductMessage.getMsgType())
                                .url(shopProductMessage.getMsgType() == 1 ? shopProductMessage.getImgUrl() : shopProductMessage.getProductOrderNo())
                                .build()
            ).collect(Collectors.toList())
            );
        }
        return ResultGenerator.genFailResult(null);
    }


    @PostMapping("/api/local/uploadCorrect")
    public Result uploadCorrect(@RequestBody ProductCorrectForm productCorrectForm) {

        try {
            logger.info("productCorrectForm=" + JsonUtil.toJson(productCorrectForm));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        localService.correctProductImg(productCorrectForm);

        return ResultGenerator.genSuccessResult();
    }



    @PostMapping(value = "/api/local/uploadRecResult", produces = APPLICATION_JSON_VALUE)
    public Result uploadRecResult(@RequestBody RecResultRequest recResultRequest) throws Exception{
        logger.info("recResultRequest=====" + JsonUtil.toJson(recResultRequest));
        long startTime = System.currentTimeMillis();
        logger.info("recWithLocation startTime=" + startTime);
        StringBuffer filePathStringBuffer = new StringBuffer("/usr/local/nginx/html/images/source/");
        filePathStringBuffer.append(recResultRequest.getShopId());

        StringBuffer outputFilepathStringBuffer = new StringBuffer("/usr/local/nginx/html/images/yppos/")
                .append(recResultRequest.getShopId());

        if (!directoryCreatedShopIdList.contains(recResultRequest.getShopId())) {
            File dirOutput = new File(outputFilepathStringBuffer.toString());
            File dir = new File(filePathStringBuffer.toString());
            directoryCreatedShopIdList.add(recResultRequest.getShopId());
            if (!dir.exists()) {
                dir.mkdir();
            }
            if (!dirOutput.exists()) {
                dirOutput.mkdir();
            }
        }

        String uuid = UUID.randomUUID().toString();

        String newFileName = filePathStringBuffer.append("/").append(uuid).append(".png").toString();

        String outputFilepath = outputFilepathStringBuffer.append("/").append(uuid).append(".result.png").toString();

        Shop shop = DataLoadService.shopMap.get(recResultRequest.getShopId());

        logger.info("shop.getProductRecType()==={}", shop.getProductRecType());
        ProductRecResultVONewWithLocation result = null;

        StringBuffer imgUrl = new StringBuffer("http://")
                .append(ipAddress)
                .append(":8019/images/yppos/")
                .append(shop.getId())
                .append("/")
                .append(uuid)
                .append(".result.png");

        byte[] bytes1 = decoder.decodeBuffer(recResultRequest.getFileContent());
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
        BufferedImage bi1 = ImageIO.read(bais);

        File f1 = new File(newFileName);
        ImageIO.write(bi1, "png", f1);


        logger.info("上传成功:newFileName==" + newFileName);

        long endTime = System.currentTimeMillis();
        logger.info("endTime=" + endTime + ", intelval=" + (endTime - startTime));


        StringBuffer sourceImgUrl = new StringBuffer("http://")
                .append(ipAddress)
                .append(":8019/images/source/")
                .append(recResultRequest.getShopId())
                .append("/")
                .append(uuid)
                .append(".png");

        String tempSourceUrl = sourceImgUrl.toString();

        Integer branchId = null;
        if (DataLoadService.deviceBranchIdMap != null) {
            branchId = DataLoadService.getBranchId(recResultRequest.getDeviceId(), recResultRequest.getShopId());
        }else {
            branchId = recResultRequest.getBranchId();
        }

        LogProductRec logProductRec = new LogProductRec();
        logProductRec.setCreateTime(new Date());
        logProductRec.setFilepath(newFileName);
        logProductRec.setOutputFilepath(outputFilepath);
        logProductRec.setShopId(shop.getId());
        logProductRec.setImgSrcNetUrl(sourceImgUrl.toString());
        logProductRec.setImgResultNetUrl(imgUrl.toString());
        if (recResultRequest.getResult() != null) {
            logProductRec.setRecResult(JsonUtil.toJson(recResultRequest.getResult()));
        }

        localService.uploadRecResult(logProductRec, recResultRequest.getResult());

        return ResultGenerator.genSuccessResult();
    }

}
